/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', 'N/file'], function (search, record, file) {
        function getInputData() {
            var mySearch = initSearch();
            var alls = [];
            var results = mySearch.run().getRange(0, 1000);
            var j = 1;
            while (results.length > 0 && j < 2) {
                for (var i = 0; i < results.length; i++) {
                    var result = results[i];
                    var tmp = {};
                    tmp.id = result.id;
                    alls[alls.length] = tmp;
                }
                results = mySearch.run().getRange(j * 1000, 1000 + j * 1000);
                j++;
            }
            //log.debug('alls', JSON.stringify(alls));
            return alls;
        }

        function map(context) {
            try {
                var recId = JSON.parse(context.value).id;
                var rec = record.load({type: 'customrecord_invalid_file_id', id: recId, isDynamic: true});
                var fileId = rec.getValue('custrecord_invalid_file_id');
                file.delete({id: fileId});
                record.delete({type: 'customrecord_invalid_file_id', id: recId,})
            } catch (e) {
                log.error('error', JSON.stringify(e));
            }

        }


        function reduce(context) {
        }

        function summarize(summary) {
        }

        function initSearch() {
            var mySearch = search.create({
                type: 'customrecord_invalid_file_id',
                filters: [['custrecord_has_delete', 'is', 'F']]
            });
            return mySearch;
        }


        return {
            getInputData: getInputData,
            map: map,
            reduce: reduce,
            summarize: summarize
        };
    }
);